package com.gitee.wsl.serialization.base

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

typealias DoubleValueP = @Serializable(with = DoubleValueSerializer::class) Double?

object DoubleValueSerializer : KSerializer<Double?> {
    @Serializable
    private data class Boxed(
        val `value`: Double = 0.0
    )

    override val descriptor: SerialDescriptor = Boxed.serializer().descriptor
    @OptIn(ExperimentalSerializationApi::class)
    override fun serialize(encoder: Encoder, value: Double?) {
        encoder.encodeNullableSerializableValue(Boxed.serializer(), value?.let { Boxed(it) })
    }

    @OptIn(ExperimentalSerializationApi::class)
    override fun deserialize(decoder: Decoder): Double? {
        return decoder.decodeNullableSerializableValue(Boxed.serializer())?.`value`
    }
}